import mockData from '@/utils/mock'
import config from '@/config'
import { logger } from '@/utils/logger'

// 是否启用mock
const enableMock = config.api.enableMock

/**
 * 模拟API请求
 * @param {string} url - 请求URL
 * @param {Object} params - 请求参数
 * @param {string} method - 请求方法
 * @returns {Promise} - 返回模拟数据
 */
export const mockRequest = async (url, params = {}, method = 'GET') => {
  if (!enableMock) {
    return Promise.reject(new Error('Mock服务未启用'))
  }

  // 记录模拟请求日志
  logger.debug(`[Mock] ${method} ${url}`, params)

  // 模拟请求延迟
  await new Promise(resolve => setTimeout(resolve, config.api.mockDelay))

  try {
    // 根据URL和方法匹配对应的模拟数据
    // 通用API
    if (url.startsWith('/common')) {
      // 获取字典数据
      if (url.startsWith('/common/dict/data/')) {
        const dictType = url.split('/').pop()
        return mockData.mockDictData(dictType)
      }
      
      // 获取学期列表
      if (url === '/common/semesters') {
        return mockData.mockSemesters()
      }
      
      // 获取当前学期
      if (url === '/common/semesters/current') {
        return mockData.mockCurrentSemester()
      }
      
      // 获取验证码
      if (url === '/common/captcha') {
        return mockData.mockSuccess({
          captchaId: Math.random().toString(36).substring(2, 10),
          captchaImage: ''
        })
      }
      
      // 上传文件
      if (url === '/common/upload' && method === 'POST') {
        return mockData.mockSuccess({
          fileName: 'uploaded_file.jpg',
          fileUrl: 'http://example.com/uploads/uploaded_file.jpg'
        }, '文件上传成功')
      }
      
      // 获取公告列表
      if (url === '/common/notices') {
        return mockData.mockSuccess([
          {
            id: 1,
            title: '关于2023-2024学年第一学期期末考试安排的通知',
            content: '期末考试将于2024年1月8日至1月19日进行，请同学们做好复习准备。',
            publishTime: '2023-12-10 10:00:00',
            publisher: '教务处'
          },
          {
            id: 2,
            title: '关于寒假放假安排的通知',
            content: '本学期教学工作于2024年1月19日结束，1月20日开始放寒假，2024年2月26日开始返校。',
            publishTime: '2023-12-15 14:30:00',
            publisher: '学生处'
          }
        ])
      }
    }
    
    // 学生API
    if (url.startsWith('/student')) {
      // 学生仪表盘
      if (url === '/student/dashboard') {
        return mockData.mockStudentDashboard()
      }
      
      // 学生信息
      if (url === '/student/info') {
        return mockData.mockStudentInfo()
      }
      
      // 课程列表
      if (url === '/student/courses') {
        return mockData.mockCourseList(params)
      }
      
      // 课表
      if (url === '/student/schedule') {
        return mockData.mockSchedule(params)
      }
      
      // 作业列表
      if (url === '/student/homework') {
        return mockData.mockHomeworkList(params)
      }
      
      // 作业课程列表
      if (url === '/student/homework/courses') {
        return mockData.mockHomeworkCourses()
      }
      
      // 作业列表（按课程）
      if (url === '/student/homework/list') {
        return mockData.mockHomeworkListByCourse(params)
      }
      
      // 考勤记录
      if (url === '/student/attendance') {
        // 如果type参数为pending，返回待签到课程
        if (params.type === 'pending') {
          return mockData.mockPendingAttendance()
        }
        return mockData.mockAttendanceRecords(params)
      }
      
      // 待签到课程
      if (url === '/student/attendance/pending') {
        return mockData.mockPendingAttendance()
      }
      
      // 考勤统计
      if (url === '/student/attendance/statistics') {
        return mockData.mockAttendanceStatistics()
      }
      
      // 签到操作
      if (url.includes('/student/attendance/sign') && method === 'POST') {
        return mockData.mockSuccess({ signInTime: new Date().toLocaleString() }, '签到成功')
      }
      
      // 成绩列表
      if (url === '/student/grades') {
        return mockData.mockGradesList(params)
      }
      
      // 选课列表
      if (url === '/student/course-selection') {
        return mockData.mockCourseList(params)
      }
      
      // 已选课程
      if (url === '/student/course-selection/selected') {
        return mockData.mockSelectedCourses()
      }
      
      // 选课记录
      if (url === '/student/course-selection/records') {
        return mockData.mockSelectionRecords()
      }
      
      // 选课操作
      if (url.includes('/student/course-selection/') && method === 'POST') {
        const courseId = url.split('/').pop()
        return mockData.mockSuccess({ courseId }, '选课成功')
      }
      
      // 退课操作
      if (url.includes('/student/course-selection/') && method === 'DELETE') {
        const courseId = url.split('/').pop()
        return mockData.mockSuccess({ courseId }, '退课成功')
      }
      
      // 资源列表
      if (url === '/student/resources') {
        return mockData.mockResourceList(params)
      }
      
      // 下载历史
      if (url === '/student/resources/download-history') {
        return mockData.mockDownloadHistory()
      }
      
      // 下载资源
      if (url.startsWith('/student/resources/download/')) {
        const resourceId = url.split('/').pop()
        return mockData.mockSuccess({ resourceId }, '文件下载已开始')
      }
      
      // 重新下载资源
      if (url.startsWith('/student/resources/redownload/')) {
        const recordId = url.split('/').pop()
        return mockData.mockSuccess({ recordId }, '文件重新下载已开始')
      }
      
      // 作业详情
      if (url.startsWith('/student/homework/') && !url.includes('submit')) {
        const homeworkId = url.split('/').pop()
        return mockData.mockSuccess({
          id: homeworkId,
          title: '高等数学第一章习题',
          courseName: '高等数学',
          teacher: '王教授',
          publishTime: '2023-09-01 08:30:00',
          deadline: '2023-09-08 23:59:59',
          content: '请完成教材第一章的习题1-10，要求写出详细的解题过程。',
          attachments: [
            {
              id: 1,
              name: '高数习题参考.pdf',
              size: '2.5MB',
              uploadTime: '2023-09-01 08:30:00'
            }
          ],
          status: '未提交',
          score: null,
          submitTime: null,
          submitContent: null,
          submitAttachments: []
        })
      }
      
      // 提交作业
      if (url.includes('/student/homework/') && url.includes('/submit') && method === 'POST') {
        const homeworkId = url.split('/')[3]
        return mockData.mockSuccess({ homeworkId }, '作业提交成功')
      }

      // 学分/成绩详情
      if (url === '/student/credits') {
        return mockData.mockCredits(params)
      }

      // 评教课程列表
      if (url === '/student/evaluation' && method === 'GET') {
        return mockData.mockEvaluationList(params)
      }
      // 评教详情
      if (url.startsWith('/student/evaluation/') && method === 'GET') {
        const id = url.split('/').pop()
        return mockData.mockEvaluationDetail(id)
      }
      // 提交评教
      if (url.startsWith('/student/evaluation/') && method === 'POST') {
        return mockData.mockSuccess({}, '评价提交成功')
      }

      // 请假记录
      if (url === '/student/leave' && method === 'GET') {
        return mockData.mockLeaveList(params)
      }
      // 提交请假
      if (url === '/student/leave' && method === 'POST') {
        return mockData.mockSuccess({}, '请假申请已提交')
      }

      // 推荐课程列表
      if (url === '/student/recommended-courses' && method === 'GET') {
        return mockData.mockRecommendedCourses(params)
      }
      // 推荐课程详情
      if (url.startsWith('/student/recommended-courses/') && method === 'GET') {
        const id = url.split('/').pop()
        return mockData.mockRecommendedCourseDetail(id)
      }
    }
    
    // 教师API
    if (url.startsWith('/teacher')) {
      // 教师仪表盘
      if (url === '/teacher/dashboard') {
        return mockData.mockSuccess({
          courseCount: 4,
          studentCount: 150,
          homeworkCount: 8,
          noticeCount: 5
        })
      }
      
      // 教师课程列表
      if (url === '/teacher/courses') {
        return mockData.mockSuccess([
          {
            id: 1,
            courseCode: 'CS101',
            courseName: '计算机导论',
            credits: 3,
            courseType: '必修',
            moduleType: '专业基础',
            semester: '2023-2024-1',
            studentCount: 45,
            classTime: '周一 1-2节',
            location: '教学楼A-101'
          },
          {
            id: 2,
            courseCode: 'CS102',
            courseName: '数据结构',
            credits: 4,
            courseType: '必修',
            moduleType: '专业核心',
            semester: '2023-2024-1',
            studentCount: 48,
            classTime: '周二 3-4节',
            location: '教学楼B-203'
          }
        ])
      }
    }
    
    // 用户API
    if (url.startsWith('/user')) {
      // 登录
      if (url === '/user/login' && method === 'POST') {
        return mockData.mockSuccess({
          token: 'mock_token_' + Date.now(),
          userInfo: {
            id: '2023001',
            name: '张三',
            role: 'student'
          }
        }, '登录成功')
      }
      
      // 用户信息
      if (url === '/user/info') {
        return mockData.mockStudentInfo()
      }
      
      // 登出
      if (url === '/user/logout' && method === 'POST') {
        return mockData.mockSuccess(null, '退出成功')
      }
      
      // 修改密码
      if (url === '/user/password' && method === 'PUT') {
        return mockData.mockSuccess(null, '密码修改成功')
      }
      
      // 修改用户信息
      if (url === '/user/info' && method === 'PUT') {
        return mockData.mockSuccess(null, '用户信息修改成功')
      }
    }
    
    // 未匹配到任何模拟数据，返回空数据
    logger.warn(`未找到匹配的模拟数据: ${method} ${url}`)
    return mockData.mockSuccess(null)
  } catch (error) {
    logger.error('模拟数据处理错误:', error)
    return Promise.reject(error)
  }
}

export default {
  mockRequest
} 